import { Repository } from "typeorm";
import { DbConfig } from "../../src/config/DbConfig";
import { GameConfig } from "../../src/config/GameConfig";
import { DaoBase } from "../../src/engine/dao/DaoBase";
import DateUtil from "../../src/engine/utils/DateUtil";
import { Logger } from "../../src/engine/utils/Logger";
import { MysqlClient } from "../../src/engine/utils/MySqlClient";
import { MysqlManager } from "../../src/engine/utils/MysqlManager";
import { JhaoProto } from "../../src/lib/net/protobuf/jhaoproto";
import { RoomEntity } from "../entity/RoomEntity";
import { RoomModel } from "../model/RoomModel";

export class RoomDao extends DaoBase {

    public static DB_NAME: string = DbConfig.Db_Name.db_game;
    public static Tb_Name: string = "t_rooms";

    public static async getRepository() {
        let repository: Repository<RoomEntity> = await this.getRepositoryBase(RoomEntity, this.getGameDbName())
        return repository;
    }


    public static async is_room_exist(roomid: string): Promise<any> {
        let client: MysqlClient = await MysqlManager.instance.getDb(this.DB_NAME);
        let sql: string = "select id from " + this.DB_NAME + "." + this.Tb_Name + " where `id`=?;"
        let sqlParams = [roomid];
        let results = await client.queryPromise(sql, sqlParams);
        if (results && results.length > 0) {
            return true
        }
        else {
            return false
        }
    }

    public static async get_club_room_count(clubid: number): Promise<number> {
        let client: MysqlClient = await MysqlManager.instance.getDb(this.DB_NAME);
        let sql: string = `select count(room_id) as count from t_rooms where clubid = ?`
        let sqlParams: Array<any> = [clubid];
        let results = await client.queryPromise(sql, sqlParams);
        // Logger.log("get_club_room_count=sql=", clubid, results)
        if (results && results.length > 0) {
            return results[0]["count"]
        }
        else {
            return 0
        }
    }

    public static async get_all_room() {
        let sql: string = "select * from  t_rooms;"
        let repository: Repository<RoomEntity> = await this.getRepository()
        let results = await repository.query(sql)
        if (results && results.length) {
            return results
        }
        return []
    }

    public static async insert_room(model: JhaoProto.IRoomModel) {
        let repository: Repository<RoomEntity> = await this.getRepository()
        let entity:RoomEntity = new RoomEntity()
        entity.room_id = model.roomId;
        entity.name = model.name;
        entity.roomType = model.roomType;
        entity.game_type = model.gameType;
        entity.creator = model.creator;
        entity.clubid = model.clubid;
        entity.num_of_turns = model.numOfTurns;
        entity.create_time = DateUtil.formatDateStr(model.createTime)
        entity.server_id = model.serverId;
        entity.conf_base = JSON.stringify(model.roomConfigBase)
        if(model.gameType == GameConfig.Game_Type.Mj){
            entity.config_game = JSON.stringify(model.roomConfigMj)
            entity.game_info_detail = JSON.stringify(model.gameInfoMj)
        }
        entity.playerList = JSON.stringify(model.playerList)
        entity.game_info_base = JSON.stringify(model.gameInfoBase)

        entity = await repository.save(entity)
        return entity
    }

    public static async clear_all_room(){
        let client: MysqlClient = await MysqlManager.instance.getDb(this.DB_NAME);
        let sql: string = "delete from t_rooms ";
        let rows = await client.queryPromise(sql);
        if (rows && rows["affectedRows"] > 0) {
            return true
        } else {
            return false
        }
    }

    public static async update_room(model: RoomModel) {
        let client: MysqlClient = await MysqlManager.instance.getDb(this.DB_NAME);
        let sql: string = "update t_rooms set `num_of_turns`=?, `playerList`=?   where `room_id`=? ";
        let sqlParams: Array<any> = [model.num_of_turns, JSON.stringify(model.playerList), model.room_id]
        let rows = await client.queryPromise(sql, sqlParams);
        if (rows && rows["affectedRows"] > 0) {
            return true
        } else {
            return false
        }
    }

    public static async delete_room(roomids: Array<number>) {
        if (roomids.length <= 0) return;
        let client: MysqlClient = await MysqlManager.instance.getDb(this.DB_NAME);
        let sql: string = "delete from t_rooms  where `room_id`=? ";
        let sqlParams: Array<any> = [roomids[0]]
        for (let i = 1; i < roomids.length; i++) {
            sql += " or `room_id`=?"
            sqlParams.push(roomids[i])
        }
        let rows = await client.queryPromise(sql, sqlParams);
        Logger.log("delete_room==", sql, sqlParams, rows)
        if (rows && rows["affectedRows"] > 0) {
            return true
        } else {
            return false
        }
    }

    public static async get_room(room_id: number) {
        let client: MysqlClient = await MysqlManager.instance.getDb(this.DB_NAME);
        let sql: string = "select * from  t_rooms where `room_id`=" + room_id
        let rows = await client.queryPromise(sql);
        if (rows && rows.length > 0) {
            return rows[0]
        }
        return null
    }

    public static async get_ziyou_room_list(gameType: number) {
        let client: MysqlClient = await MysqlManager.instance.getDb(this.DB_NAME);
        let sql: string = "select * from  t_rooms where `room_type`=4 and `gameType`=?"
        let sqlParams: Array<any> = [gameType]
        let rows = await client.queryPromise(sql, sqlParams);
        if (rows && rows.length > 0) {
            return rows
        }
        return []
    }

}